<?php

namespace app\common\model;

use think\Db;
use think\Model;

/**
 * 订单模型
 */
class Order extends Model
{

    // 表名
    protected $name = 'order';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    public function order_add($user_id, $order){

        $order_no = $this->orderNo();
        $order['user_id'] = $user_id;
        if($order['juan_id']){
            $now_time = time();
            $jian_time = $now_time-604800;

            $juan_data = Db::name('juan')->where(['id'=>$order['juan_id']])->find();
            if($juan_data['state']=='1'){
                return 2;//已使用
            }

            if($juan_data['createtime']<$jian_time){
                return 3;//expired
            }

            $order['pay_type'] = 10;
            $order['pay_status'] = 20;

        }else{
            $order['pay_type'] = 20; 
        }
        $order['total_price'] = 1;
        $order['order_no'] = $order_no;
        unset($order['juan_id']);
        $add_id = $this->save($order);

        empty($add_id);
        Db::commit();
        return $order;
    }

    protected function orderNo()
    {
        return 'WM'.date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

}
